package com.example.getfollowlist.service

import android.accessibilityservice.AccessibilityService
import android.content.Intent
import android.graphics.Rect
import android.os.Handler
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.Toast

/**
 * 导航任务类
 * 
 * 负责处理从抖音首页导航到关注列表页面的过程。
 * 包含两个主要步骤：
 * 1. 点击底部导航栏的"我"按钮
 * 2. 点击个人主页的"关注"按钮
 * 3. 等待2秒后自动开始下一个任务
 */
class NavigationTask(
    private val service: AccessibilityService,
    private val handler: Handler,
    private val onNavigationComplete: () -> Unit
) {
    // 导航状态控制
    private var currentStep = 0
    private var lastClickTime = 0L
    private val CLICK_DELAY = 1000L
    private var isProcessingClick = false

    companion object {
        private const val TAG = "GetFollowList"
    }

    /**
     * 启动导航任务
     * 初始化状态并启动抖音应用
     */
    fun start() {
        currentStep = 0
        lastClickTime = 0L
        isProcessingClick = false
        
        // 启动抖音应用
        val launchIntent = service.packageManager.getLaunchIntentForPackage("com.ss.android.ugc.aweme")
        if (launchIntent != null) {
            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            service.startActivity(launchIntent)
            Log.d(TAG, "已启动抖音APP")
            Toast.makeText(service, "启动抖音", Toast.LENGTH_SHORT).show()
        } else {
            Log.e(TAG, "未安装抖音或无法启动")
            Toast.makeText(service, "未安装抖音或无法启动", Toast.LENGTH_LONG).show()
        }
    }

    /**
     * 处理无障碍事件
     * 根据当前步骤执行相应的操作
     */
    fun handleEvent(event: AccessibilityEvent, root: AccessibilityNodeInfo) {
        if (isProcessingClick) return

        Log.d(TAG, "处理导航事件: ${event.eventType}, 当前步骤: $currentStep")

        val currentTime = System.currentTimeMillis()
        if (currentTime - lastClickTime < CLICK_DELAY) return

        when (currentStep) {
            0 -> handleMeButton(root)      // 处理"我"按钮点击
            1 -> handleFollowButton(root)  // 处理"关注"按钮点击
        }
    }

    /**
     * 处理"我"按钮的点击
     * 查找并点击底部导航栏的"我"按钮
     */
    private fun handleMeButton(root: AccessibilityNodeInfo) {
        Log.d(TAG, "尝试查找并点击底部栏的'我'按钮")
        val meButton = findBottomTabMe(root)
        if (meButton != null) {
            performClick(meButton, "我") {
                currentStep = 1
            }
        }
    }

    /**
     * 处理"关注"按钮的点击
     * 在个人主页中查找并点击"关注"按钮
     * 点击后等待2秒自动开始下一个任务
     */
    private fun handleFollowButton(root: AccessibilityNodeInfo) {
        Log.d(TAG, "尝试查找并点击'关注'按钮")
        val followButton = findNodeByText(root, "关注")
        val inProfilePage = isInProfilePage(root)
        
        if (followButton != null && inProfilePage) {
            performClick(followButton, "关注") {
                currentStep = 2
                // 点击后等待2秒直接开始下一个任务
                handler.postDelayed({
                    Log.d(TAG, "点击关注按钮后等待2秒，开始下一个任务")
                    onNavigationComplete()
                }, 2000)
            }
        }
    }


    /**
     * 查找底部导航栏的"我"按钮
     * 通过位置信息和相邻的"消息"按钮来确定正确的"我"按钮
     */
    private fun findBottomTabMe(root: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        try {
            val screenHeight = service.resources.displayMetrics.heightPixels
            val meNodes = root.findAccessibilityNodeInfosByText("我")
            val messageNodes = root.findAccessibilityNodeInfosByText("消息")

            val sortedMeNodes = meNodes.sortedByDescending { node ->
                val rect = Rect()
                node.getBoundsInScreen(rect)
                rect.bottom
            }

            for (meNode in sortedMeNodes) {
                val meRect = Rect()
                meNode.getBoundsInScreen(meRect)
                
                val isAtBottom = meRect.bottom > screenHeight * 0.8

                if (isAtBottom) {
                    for (messageNode in messageNodes) {
                        val messageRect = Rect()
                        messageNode.getBoundsInScreen(messageRect)
                        
                        val isMessageOnLeft = messageRect.right < meRect.left
                        val isSameHeight = Math.abs(messageRect.bottom - meRect.bottom) < 50

                        if (isMessageOnLeft && isSameHeight) {
                            return meNode
                        }
                    }
                }
            }
            return null
        } catch (e: Exception) {
            Log.e(TAG, "查找底部栏'我'按钮时发生错误: ${e.message}")
            return null
        }
    }

    /**
     * 执行点击操作
     * 处理节点的点击事件，包括延时和状态更新
     */
    private fun performClick(node: AccessibilityNodeInfo, buttonName: String, onSuccess: () -> Unit) {
        isProcessingClick = true
        handler.postDelayed({
            try {
                if (node.isClickable) {
                    node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                } else {
                    var parent = node.parent
                    while (parent != null) {
                        if (parent.isClickable) {
                            parent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                            break
                        }
                        parent = parent.parent
                    }
                }
                lastClickTime = System.currentTimeMillis()
                onSuccess()
                Log.d(TAG, "已点击'$buttonName'按钮，步骤推进到: $currentStep")
                Toast.makeText(service, "点击'$buttonName'按钮", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                Log.e(TAG, "点击'$buttonName'按钮时发生错误: ${e.message}")
            }
            isProcessingClick = false
        }, CLICK_DELAY)
    }

    /**
     * 通过文本查找节点
     */
    private fun findNodeByText(root: AccessibilityNodeInfo, text: String): AccessibilityNodeInfo? {
        val nodes = root.findAccessibilityNodeInfosByText(text)
        return nodes.firstOrNull()
    }

    /**
     * 检查是否在个人主页
     * 通过检查特定元素的存在来确认
     */
    private fun isInProfilePage(root: AccessibilityNodeInfo): Boolean {
        try {
            val hasFans = root.findAccessibilityNodeInfosByText("粉丝").isNotEmpty()
            val hasFollow = root.findAccessibilityNodeInfosByText("关注").isNotEmpty()
            val hasWorks = root.findAccessibilityNodeInfosByText("作品").isNotEmpty()
            return hasFans && hasFollow && hasWorks
        } catch (e: Exception) {
            Log.e(TAG, "检查个人页面时发生错误: ${e.message}")
            return false
        }
    }
}